package com.frxuexi.lib_base.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.frxuexi.lib_base.entity.Res
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

open class BaseViewModel :ViewModel(){

    /**
     * 网络请求
     * s:网络请求接口
     * success：响应成功时把结果回调出去
     */
    fun <T> httpRequest(s:suspend ()->Res<T>,success:(T)->Unit){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val res = s.invoke()
                if(res.code==200){
                    success(res.data)
                }else{
                    Log.i("lr",res.message?:res.msg)
                }
            }catch (e:Exception){
                Log.i("lr",e.message.toString())
            }
        }
    }

    fun <T> roomRequest(s:()->T,success:(T)->Unit){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                val res = s.invoke()
                if(res!=null){
                    success(res)
                }else{
                    Log.i("lr","操作失败")
                }
            }catch (e:Exception){
                Log.i("lr",e.message.toString())
            }
        }
    }

    fun toBody(item:Any):RequestBody{
        val json = Gson().toJson(item)
        return RequestBody.create("application/json".toMediaTypeOrNull(),json)
    }

    fun getDateTimeString(time:Long):String{
        return SimpleDateFormat("yyyyMMddHHmmss").format(time)
    }

    fun getDateTime(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }

    fun getTime(time:Long):String{
        return SimpleDateFormat("HH:mm:ss").format(time)
    }

    fun getDateFont(time:Long):String{
        return SimpleDateFormat("yyyy年MM月dd").format(time)
    }

    fun getDate(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd").format(time)
    }
}